/**
 * API 权限验证中间件
 * 
 * 提供统一的身份验证和权限检查功能
 */

import { NextRequest, NextResponse } from 'next/server'
import { verifyToken, getUserInfo } from './auth-service'

export interface AuthenticatedUser {
  id: string
  email: string
  name: string
  role: 'USER' | 'ADMIN'
}

export interface AuthenticatedRequest extends NextRequest {
  user?: AuthenticatedUser
}

/**
 * 从请求中提取JWT token
 */
function extractToken(request: NextRequest): string | null {
  console.log('开始提取token...')
  
  // 1. 从 Authorization header 获取
  const authHeader = request.headers.get('authorization')
  if (authHeader && authHeader.startsWith('Bearer ')) {
    console.log('从Authorization header获取到token')
    return authHeader.substring(7)
  }

  // 2. 从 cookie 获取
  const cookieToken = request.cookies.get('auth-token')?.value
  if (cookieToken) {
    console.log('从cookie获取到token')
    return cookieToken
  }

  console.log('未找到token')
  return null
}

/**
 * 验证JWT token并获取用户信息
 */
async function verifyTokenMiddleware(token: string): Promise<AuthenticatedUser | null> {
  try {
    // 验证token
    const decoded = verifyToken(token)
    if (!decoded) {
      return null
    }

    // 从数据库获取最新用户信息
    const user = await getUserInfo(decoded.id)
    if (!user) {
      return null
    }

    return {
      id: user.id,
      email: user.email,
      name: user.name,
      role: user.role as 'USER' | 'ADMIN'
    }
  } catch (error) {
    console.error('Token 验证失败:', error)
    return null
  }
}

/**
 * 身份验证中间件
 * 验证用户是否已登录
 */
export async function requireAuth(
  request: NextRequest,
  handler: (req: AuthenticatedRequest) => Promise<NextResponse>
): Promise<NextResponse> {
  console.log('requireAuth: 开始验证用户身份')
  const token = extractToken(request)
  
  if (!token) {
    console.log('requireAuth: 未提供认证token')
    return NextResponse.json(
      { error: '未提供认证token' },
      { status: 401 }
    )
  }

  const user = await verifyTokenMiddleware(token)
  if (!user) {
    console.log('requireAuth: 无效的认证token')
    return NextResponse.json(
      { error: '无效的认证token' },
      { status: 401 }
    )
  }

  console.log('requireAuth: 用户验证成功', { 
    userId: user.id, 
    userEmail: user.email, 
    userRole: user.role 
  })

  // 将用户信息添加到请求对象
  const authenticatedRequest = request as AuthenticatedRequest
  authenticatedRequest.user = user

  return handler(authenticatedRequest)
}

/**
 * 管理员权限中间件
 * 验证用户是否为管理员
 */
export async function requireAdmin(
  request: NextRequest,
  handler: (req: AuthenticatedRequest) => Promise<NextResponse>
): Promise<NextResponse> {
  return requireAuth(request, async (req) => {
    if (req.user?.role !== 'ADMIN') {
      return NextResponse.json(
        { error: '需要管理员权限' },
        { status: 403 }
      )
    }
    return handler(req)
  })
}

/**
 * 资源所有者权限中间件
 * 验证用户是否为资源所有者或管理员
 */
export async function requireOwnerOrAdmin(
  request: NextRequest,
  resourceUserId: string,
  handler: (req: AuthenticatedRequest) => Promise<NextResponse>
): Promise<NextResponse> {
  return requireAuth(request, async (req) => {
    const user = req.user!
    
    if (user.role !== 'ADMIN' && user.id !== resourceUserId) {
      return NextResponse.json(
        { error: '权限不足：只能操作自己的资源' },
        { status: 403 }
      )
    }
    
    return handler(req)
  })
}

/**
 * 可选身份验证中间件
 * 如果提供了token则验证，否则继续执行
 */
export async function optionalAuth(
  request: NextRequest,
  handler: (req: AuthenticatedRequest) => Promise<NextResponse>
): Promise<NextResponse> {
  const token = extractToken(request)
  
  if (token) {
    const user = await verifyToken(token)
    if (user) {
      const authenticatedRequest = request as AuthenticatedRequest
      authenticatedRequest.user = user
    }
  }

  return handler(request as AuthenticatedRequest)
}

/**
 * 速率限制中间件（简单实现）
 */
const rateLimitMap = new Map<string, { count: number; resetTime: number }>()

export async function rateLimit(
  request: NextRequest,
  options: { maxRequests: number; windowMs: number } = { maxRequests: 100, windowMs: 15 * 60 * 1000 },
  handler: (req: NextRequest) => Promise<NextResponse>
): Promise<NextResponse> {
  const clientIp = request.headers.get('x-forwarded-for') || 'unknown'
  const now = Date.now()
  const windowStart = now - options.windowMs

  // 清理过期的记录
  for (const [key, value] of rateLimitMap.entries()) {
    if (value.resetTime < now) {
      rateLimitMap.delete(key)
    }
  }

  // 检查当前IP的请求次数
  const current = rateLimitMap.get(clientIp) || { count: 0, resetTime: now + options.windowMs }
  
  if (current.count >= options.maxRequests && current.resetTime > now) {
    return NextResponse.json(
      { error: '请求过于频繁，请稍后再试' },
      { status: 429 }
    )
  }

  // 更新请求计数
  current.count++
  rateLimitMap.set(clientIp, current)

  return handler(request)
}


/**
 * 组合多个中间件
 */
export function withMiddleware(
  ...middlewares: Array<(req: NextRequest, handler: any) => Promise<NextResponse>>
) {
  return (handler: (req: NextRequest) => Promise<NextResponse>) => {
    return middlewares.reduceRight(
      (acc, middleware) => (req: NextRequest) => middleware(req, acc),
      handler
    )
  }
}

/**
 * 错误处理包装器
 */
export function withErrorHandling(
  handler: (request: NextRequest) => Promise<NextResponse>
): (request: NextRequest) => Promise<NextResponse> {
  return async (request: NextRequest) => {
    try {
      return await handler(request)
    } catch (error) {
      console.error('API错误:', error)
      return NextResponse.json(
        { error: '服务器内部错误' },
        { status: 500 }
      )
    }
  }
}
